<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blogwebpage/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blogwebpage/images/favicon.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/blogwebpage/images/favicon.ico">
  <link rel="mask-icon" href="/blogwebpage/images/logo.svg" color="#222">
  <meta name="msvalidate.01" content="9BDlx6FiNE">

<link rel="stylesheet" href="/blogwebpage/css/main.css">


<link rel="stylesheet" href="/blogwebpage/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"wangkejie.gitee.io","root":"/blogwebpage/","scheme":"Gemini","version":"7.8.0","exturl":true,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"default"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="在运行时创建一个类123Class newClass &#x3D; objc_allocateClassPair([NSError class], &quot;RuntimeErrorSubclass&quot;, 0);class_addMethod(newClass, @selector(report), (IMP)ReportFunction, &quot;v@:&quot;);objc_regist">
<meta property="og:type" content="article">
<meta property="og:title" content="Objective-C中的元类是什么？">
<meta property="og:url" content="https://wangkejie.gitee.io/blogwebpage/iOS/origincode/metaclass.html">
<meta property="og:site_name" content="王科杰">
<meta property="og:description" content="在运行时创建一个类123Class newClass &#x3D; objc_allocateClassPair([NSError class], &quot;RuntimeErrorSubclass&quot;, 0);class_addMethod(newClass, @selector(report), (IMP)ReportFunction, &quot;v@:&quot;);objc_regist">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2017-10-10T03:26:39.000Z">
<meta property="article:modified_time" content="2021-06-25T08:55:53.148Z">
<meta property="article:author" content="Jack Wang">
<meta property="article:tag" content="iOS源码学习">
<meta property="article:tag" content="元类是什么">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://wangkejie.gitee.io/blogwebpage/iOS/origincode/metaclass.html">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>Objective-C中的元类是什么？ | 王科杰</title>
  


  <script>
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?93e26277de0cf2c5851167f2c6dcaa7d";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blogwebpage/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">王科杰</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Jack's Notes</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blogwebpage/" rel="section"><i class="home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blogwebpage/archives/" rel="section"><i class="archive fa-fw"></i>归档<span class="badge">52</span></a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blogwebpage/me/" rel="section"><i class="user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blogwebpage/tags/" rel="section"><i class="tags fa-fw"></i>标签<span class="badge">54</span></a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blogwebpage/categories/" rel="section"><i class="th fa-fw"></i>分类<span class="badge">56</span></a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>

  <span class="exturl github-corner" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></span>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://wangkejie.gitee.io/blogwebpage/iOS/origincode/metaclass.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blogwebpage/images/avatar.gif">
      <meta itemprop="name" content="Jack Wang">
      <meta itemprop="description" content="书山有路勤为径，学海无涯苦作舟！">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="王科杰">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          Objective-C中的元类是什么？
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-10-10 11:26:39" itemprop="dateCreated datePublished" datetime="2017-10-10T11:26:39+08:00">2017-10-10</time>
            </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/" itemprop="url" rel="index"><span itemprop="name">iOS</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E6%BA%90%E7%A0%81%E5%AD%A6%E4%B9%A0/" itemprop="url" rel="index"><span itemprop="name">源码学习</span></a>
                </span>
                  ，
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blogwebpage/categories/iOS/%E6%BA%90%E7%A0%81%E5%AD%A6%E4%B9%A0/%E5%85%83%E7%B1%BB%E6%98%AF%E4%BB%80%E4%B9%88/" itemprop="url" rel="index"><span itemprop="name">元类是什么</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="在运行时创建一个类"><a href="#在运行时创建一个类" class="headerlink" title="在运行时创建一个类"></a>在运行时创建一个类</h1><figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">Class newClass = objc_allocateClassPair([<span class="built_in">NSError</span> <span class="keyword">class</span>], <span class="string">&quot;RuntimeErrorSubclass&quot;</span>, <span class="number">0</span>);</span><br><span class="line">class_addMethod(newClass, <span class="keyword">@selector</span>(report), (IMP)ReportFunction, <span class="string">&quot;v@:&quot;</span>);</span><br><span class="line">objc_registerClassPair(newClass);</span><br></pre></td></tr></table></figure>

<p>添加的方法使用名为ReportFunction其实现的函数，其定义如下：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">void</span> ReportFunction(<span class="keyword">id</span> <span class="keyword">self</span>, SEL _cmd)</span><br><span class="line">&#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;This object is %p.&quot;</span>, <span class="keyword">self</span>);</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;Class is %@, and super is %@.&quot;</span>, [<span class="keyword">self</span> <span class="keyword">class</span>], [<span class="keyword">self</span> superclass]);</span><br><span class="line">    </span><br><span class="line">    Class currentClass = [<span class="keyword">self</span> <span class="keyword">class</span>];</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">int</span> i = <span class="number">1</span>; i &lt; <span class="number">5</span>; i++)</span><br><span class="line">    &#123;</span><br><span class="line">        <span class="built_in">NSLog</span>(<span class="string">@&quot;Following the isa pointer %d times gives %p&quot;</span>, i, currentClass);</span><br><span class="line">        currentClass = object_getClass(currentClass);</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;NSObject&#x27;s class is %p&quot;</span>, [<span class="built_in">NSObject</span> <span class="keyword">class</span>]);</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;NSObject&#x27;s meta class is %p&quot;</span>, object_getClass([<span class="built_in">NSObject</span> <span class="keyword">class</span>]));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>从表面上看，这一切都非常简单。在运行时创建类只需三个简单的步骤：</p>
<ul>
<li>为“类对”分配存储（使用objc_allocateClassPair）。</li>
<li>根据需要将方法和ivars添加到类中（我添加了一个方法class_addMethod）。</li>
<li>注册该类以便可以使用（使用objc_registerClassPair）。</li>
</ul>
<p>然而，当前的问题是：什么是“class pair”？该函数objc_allocateClassPair只返回一个值：类。那对的另一半在哪里？</p>
<p>我敢肯定你已经猜到了这一对的另一半是元类（这是这篇文章的标题）但是为了解释这是什么以及你为什么需要它，我将给出一些关于对象的背景知识和Objective-C中的类。</p>
<h1 id="成为对象de数据结构需要什么？"><a href="#成为对象de数据结构需要什么？" class="headerlink" title="成为对象de数据结构需要什么？"></a>成为对象de数据结构需要什么？</h1><p>在Objective-C中，对象的类由其isa指针确定。该isa指针指向对象的类。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="keyword">struct</span> objc_object &#123;</span><br><span class="line">    Class isa;</span><br><span class="line">&#125; *<span class="keyword">id</span>;</span><br></pre></td></tr></table></figure>
<p>这就是说：任何以指向Class结构的指针开头的结构都可以视为objc_object。</p>
<p>Objective-C中对象最重要的特性是你可以向它们发送消息：</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">[<span class="string">@&quot;stringValue&quot;</span></span><br><span class="line">    writeToFile:<span class="string">@&quot;/file.txt&quot;</span> atomically:<span class="literal">YES</span> encoding:<span class="built_in">NSUTF8StringEncoding</span> error:<span class="literal">NULL</span>];</span><br></pre></td></tr></table></figure>

<h1 id="什么是元级？"><a href="#什么是元级？" class="headerlink" title="什么是元级？"></a>什么是元级？</h1><p>现在，正如您可能已经知道的那样，Class 在Objective-C中也是一个对象。这意味着您可以发送消息给Class。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSStringEncoding</span> defaultStringEncoding = [<span class="built_in">NSString</span> defaultStringEncoding];</span><br></pre></td></tr></table></figure>
<p>在这种情况下，defaultStringEncoding被发送到NSString class。</p>
<p>这是有效的，因为Class 在Objective-C中的每个都是一个对象本身。这意味着Class结构必须以isa指针开头，以便它与objc_object上面显示的结构二进制兼容，并且结构中的下一个字段必须是指向superclass（或nil基类）的指针。</p>
<p>正如我上面所展示的那样Class，根据您运行的运行时版本，有几种不同的方式可以定义，但是，它们都以isa字段后跟字段开头superclass。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="keyword">struct</span> objc_class *Class;</span><br><span class="line"><span class="keyword">struct</span> objc_class &#123;</span><br><span class="line">    Class isa;</span><br><span class="line">    Class super_class;</span><br><span class="line">    <span class="comment">/* followed by runtime specific details... */</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<p>但是，为了让我们调用类上的方法，类的isa指针本身必须指向一个类结构，而这个类结构必须包含我们可以在类上调用的方法列表。</p>
<p>这就引出了元类的定义:元类是类对象的类。</p>
<p>简单地说:</p>
<ul>
<li>当您向对象发送消息时，将在对象类的方法列表中查找该消息。</li>
<li>当您向类发送消息时，将在类的元类的方法列表中查找该消息。</li>
</ul>
<p>元类非常重要，因为它存储类的类方法。每个类必须有一个惟一的元类，因为每个类都有一个潜在惟一的类方法列表。</p>
<h1 id="元类的类是什么"><a href="#元类的类是什么" class="headerlink" title="元类的类是什么?"></a>元类的类是什么?</h1><p>与之前的类一样，元类也是一个对象。这意味着您也可以在其上调用方法。当然，这意味着它还必须有一个类。</p>
<p>所有元类都使用<code>基类的元类</code>(继承层次结构中顶层类的元类)作为<code>类</code>。这意味着对于从NSObject派生的所有类(大多数类)，<code>元类</code>都将<code>NSObject元类</code>作为其<code>类</code>。</p>
<p>遵循所有元类都使用基类的元类作为它们的类的规则，任何基元类都将是它自己的类(它们的isa指针指向它们自己)。这意味着NSObject元类上的isa指针指向它自己(它是它自己的一个实例)。</p>
<h1 id="类和元类的继承"><a href="#类和元类的继承" class="headerlink" title="类和元类的继承"></a>类和元类的继承</h1><p>就像类用它的超类指针指向超类一样，元类使用它自己的超类指针指向类的超类的元类。</p>
<p>更奇怪的是，<code>基类</code>的<code>元类</code>将其<code>超类</code>设置为<code>基类本身</code>。</p>
<p>这种继承层次结构的结果是，层次结构中的所有实例、类和元类都继承自层次结构的基类。</p>
<p>对于NSObject层次结构中的所有实例、类和元类，这意味着所有NSObject实例方法都是有效的。对于类和元类，所有NSObject类方法也是有效的。</p>
<p>所有这些在文本中都很混乱。Greg Parker将实例、类、元类和它们的超类以及它们是如何组合在一起的组成了一个很好的图表。</p>
<h1 id="这一点的实验证实"><a href="#这一点的实验证实" class="headerlink" title="这一点的实验证实"></a>这一点的实验证实</h1><p>为了确认这一切，让我们看看我在本文开头给出的ReportFunction的输出。这个函数的目的是跟踪isa指针并记录它所发现的内容。</p>
<p>要运行ReportFunction，我们需要创建动态创建的类的实例，并在其上调用report方法。</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">id</span> instanceOfNewClass = [[newClass alloc] initWithDomain:<span class="string">@&quot;someDomain&quot;</span> code:<span class="number">0</span> userInfo:<span class="literal">nil</span>];</span><br><span class="line">[instanceOfNewClass performSelector:<span class="keyword">@selector</span>(report)];</span><br><span class="line">[instanceOfNewClass release];</span><br></pre></td></tr></table></figure>

<p>由于报表方法没有声明，所以我使用performSelector:调用它，因此编译器不会给出警告。</p>
<p>ReportFunction现在将遍历isa指针，并告诉我们使用哪些对象作为类、元类和元类的类。</p>
<blockquote>
<p>获取对象的类:ReportFunction使用object_getClass跟踪isa指针，因为isa指针是该类的受保护成员(您不能直接访问其他对象的isa指针)。ReportFunction不使用类方法来实现这一点，因为在类对象上调用类方法不会返回元类，而是再次返回类(因此[NSString类]将返回NSString类而不是NSString元类)。</p>
</blockquote>
<p>This is the output (minus NSLog prefixes) when the program runs:</p>
<figure class="highlight objc"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">This object is <span class="number">0x10010c810</span>.</span><br><span class="line">Class is RuntimeErrorSubclass, and <span class="keyword">super</span> is <span class="built_in">NSError</span>.</span><br><span class="line">Following the isa pointer <span class="number">1</span> times gives <span class="number">0x10010c600</span></span><br><span class="line">Following the isa pointer <span class="number">2</span> times gives <span class="number">0x10010c630</span></span><br><span class="line">Following the isa pointer <span class="number">3</span> times gives <span class="number">0x7fff71038480</span></span><br><span class="line">Following the isa pointer <span class="number">4</span> times gives <span class="number">0x7fff71038480</span></span><br><span class="line"><span class="built_in">NSObject</span><span class="string">&#x27;s class is 0x7fff71038490</span></span><br><span class="line"><span class="string">NSObject&#x27;</span>s meta <span class="keyword">class</span> is <span class="number">0x7fff71038480</span></span><br></pre></td></tr></table></figure>

<p>反复查看isa值所达到的地址:</p>
<ul>
<li>对象是地址0x10010c810。</li>
<li>类的地址是0x10010c600。</li>
<li>元类是地址0x10010c630。</li>
<li>元类的类(即NSObject元类)是地址0x7fff71038480。</li>
<li>NSObject元类的类是它自己。</li>
</ul>
<p>地址的值并不十分重要，除非它显示了从类到元类到NSObject元类的过程。</p>
<h1 id="总结"><a href="#总结" class="headerlink" title="总结"></a>总结</h1><p>元类是类对象的类。每个类都有自己独特的元类(因为每个类都可以有自己独特的方法列表)。这意味着所有类对象本身并不都属于同一个类。</p>
<p>元类将始终确保类对象具有层次结构中基类的所有实例和类方法，以及中间的所有类方法。对于派生自NSObject的类，这意味着所有NSObject实例和协议方法都为所有类(和元类)对象定义。</p>
<p>所有元类本身都使用基类的元类(NSObject层次结构类的NSObject元类)作为类，包括运行时中惟一自定义的基类元类。</p>

    </div>

    
    
    
        <div class="reward-container">
  <div>希望对您有所帮助，您的支持将是我莫大的动力！</div>
  <button onclick="var qr = document.getElementById('qr'); qr.style.display = (qr.style.display === 'none') ? 'block' : 'none';">
    打赏
  </button>
  <div id="qr" style="display: none;">
      
      <div style="display: inline-block;">
        <img src="/blogwebpage/images/wechatpay.png" alt="Jack Wang 微信支付">
        <p>微信支付</p>
      </div>
      
      <div style="display: inline-block;">
        <img src="/blogwebpage/images/alipay.png" alt="Jack Wang 支付宝">
        <p>支付宝</p>
      </div>

  </div>
</div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/blogwebpage/tags/iOS%E6%BA%90%E7%A0%81%E5%AD%A6%E4%B9%A0/" rel="tag"># iOS源码学习</a>
              <a href="/blogwebpage/tags/%E5%85%83%E7%B1%BB%E6%98%AF%E4%BB%80%E4%B9%88/" rel="tag"># 元类是什么</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/blogwebpage/iOS/origincode/origincodestudy.html" rel="prev" title="iOS类的本质">
      <i class="fa fa-chevron-left"></i> iOS类的本质
    </a></div>
      <div class="post-nav-item">
    <a href="/blogwebpage/iOS/origincode/dispatch_once.html" rel="next" title="dispatch_once">
      dispatch_once <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%9C%A8%E8%BF%90%E8%A1%8C%E6%97%B6%E5%88%9B%E5%BB%BA%E4%B8%80%E4%B8%AA%E7%B1%BB"><span class="nav-number">1.</span> <span class="nav-text">在运行时创建一个类</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%88%90%E4%B8%BA%E5%AF%B9%E8%B1%A1de%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E9%9C%80%E8%A6%81%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="nav-number">2.</span> <span class="nav-text">成为对象de数据结构需要什么？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BB%80%E4%B9%88%E6%98%AF%E5%85%83%E7%BA%A7%EF%BC%9F"><span class="nav-number">3.</span> <span class="nav-text">什么是元级？</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%85%83%E7%B1%BB%E7%9A%84%E7%B1%BB%E6%98%AF%E4%BB%80%E4%B9%88"><span class="nav-number">4.</span> <span class="nav-text">元类的类是什么?</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E7%B1%BB%E5%92%8C%E5%85%83%E7%B1%BB%E7%9A%84%E7%BB%A7%E6%89%BF"><span class="nav-number">5.</span> <span class="nav-text">类和元类的继承</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%BF%99%E4%B8%80%E7%82%B9%E7%9A%84%E5%AE%9E%E9%AA%8C%E8%AF%81%E5%AE%9E"><span class="nav-number">6.</span> <span class="nav-text">这一点的实验证实</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%80%BB%E7%BB%93"><span class="nav-number">7.</span> <span class="nav-text">总结</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Jack Wang"
      src="/blogwebpage/images/avatar.gif">
  <p class="site-author-name" itemprop="name">Jack Wang</p>
  <div class="site-description" itemprop="description">书山有路勤为径，学海无涯苦作舟！</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blogwebpage/archives/">
        
          <span class="site-state-item-count">52</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blogwebpage/categories/">
          
        <span class="site-state-item-count">56</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blogwebpage/tags/">
          
        <span class="site-state-item-count">54</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <span class="exturl" data-url="aHR0cHM6Ly9naXRodWIuY29tL0phY2stVmluZw==" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;Jack-Ving"><i class="github fa-fw"></i>GitHub</span>
      </span>
      <span class="links-of-author-item">
        <span class="exturl" data-url="bWFpbHRvOjcyNzg4MTk0NUBxcS5jb20=" title="E-Mail → mailto:727881945@qq.com"><i class="envelope fa-fw"></i>E-Mail</span>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        
  <div class="beian"><span class="exturl" data-url="aHR0cHM6Ly9iZWlhbi5taWl0Lmdvdi5jbg==">京ICP备16036665号-2 </span>
  </div>

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Jack Wang</span>
</div>
  <div class="powered-by">由 <span class="exturl theme-link" data-url="aHR0cHM6Ly9oZXhvLmlv">Hexo</span> & <span class="exturl theme-link" data-url="aHR0cHM6Ly90aGVtZS1uZXh0Lm9yZw==">NexT.Gemini</span> 强力驱动
  </div>

        


  <div style="display: none;">
    <script src="//s95.cnzz.com/z_stat.php?id=1277804316&web_id=1277804316"></script>
  </div>






      </div>
    </footer>
  </div>

  
  <script src="/blogwebpage/lib/anime.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.min.js"></script>
  <script src="/blogwebpage/lib/velocity/velocity.ui.min.js"></script>

<script src="/blogwebpage/js/utils.js"></script>

<script src="/blogwebpage/js/motion.js"></script>


<script src="/blogwebpage/js/schemes/pisces.js"></script>


<script src="/blogwebpage/js/next-boot.js"></script>




  
  <script>
    (function(){
      var canonicalURL, curProtocol;
      //Get the <link> tag
      var x=document.getElementsByTagName("link");
		//Find the last canonical URL
		if(x.length > 0){
			for (i=0;i<x.length;i++){
				if(x[i].rel.toLowerCase() == 'canonical' && x[i].href){
					canonicalURL=x[i].href;
				}
			}
		}
    //Get protocol
	    if (!canonicalURL){
	    	curProtocol = window.location.protocol.split(':')[0];
	    }
	    else{
	    	curProtocol = canonicalURL.split(':')[0];
	    }
      //Get current URL if the canonical URL does not exist
	    if (!canonicalURL) canonicalURL = window.location.href;
	    //Assign script content. Replace current URL with the canonical URL
      !function(){var e=/([http|https]:\/\/[a-zA-Z0-9\_\.]+\.baidu\.com)/gi,r=canonicalURL,t=document.referrer;if(!e.test(r)){var n=(String(curProtocol).toLowerCase() === 'https')?"https://sp0.baidu.com/9_Q4simg2RQJ8t7jm9iCKT-xh_/s.gif":"//api.share.baidu.com/s.gif";t?(n+="?r="+encodeURIComponent(document.referrer),r&&(n+="&l="+r)):r&&(n+="?l="+r);var i=new Image;i.src=n}}(window);})();
  </script>




  
<script src="/blogwebpage/js/local-search.js"></script>













  

  

</body>
</html>
